package cjgl.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import cjgl.entity.TbClass;

public class TbClassDAO {
	public TbClass findById(Integer id) {
		TbClass tbClass = null;
		String sql="select * from tbClass t where t.id="+id;
		Connection conn = ConnectionFactory.getConnection();
		if(conn!=null) {
		Statement stmt;
		try {
			stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			if(rs.next()) {
				tbClass = new TbClass(rs.getInt(1), rs.getString(2),rs.getString(3));
			}
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		}
		return tbClass;
	}
	
	public List<TbClass> findAll(){
		List<TbClass> list = new ArrayList<TbClass>();
		String sql = "select * from tbClass";
		Connection conn = ConnectionFactory.getConnection();
		if(conn!=null) {
		try {
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			while(rs.next()) {
				TbClass bj=new TbClass(rs.getInt(1), rs.getString(2),rs.getString(3));
				list.add(bj);
			}
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		}
		return list;
		
	}
	
	public synchronized void insert(TbClass tbClass) {
		String sql="insert into tbclass values(null,?,?)";
		Connection conn = ConnectionFactory.getConnection();
		if(conn!=null) {
		PreparedStatement pstmt;
		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, tbClass.getName());
			pstmt.setString(2, tbClass.getManager());
			pstmt.execute();
			sql="select * from tbClass t order by t.id desc";
			ResultSet rs = pstmt.executeQuery(sql);
			rs.next();
			tbClass.setId(rs.getInt(1));
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		}
	}
	
	public void update(TbClass tbClass) {
		String sql = "update tbclass t set t.name=?,t.manager=? where t.id=?";
		Connection conn = ConnectionFactory.getConnection();
		if(conn!=null) {
			PreparedStatement pstmt;
			try {
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, tbClass.getName());
				pstmt.setString(2, tbClass.getManager());
				pstmt.setInt(3, tbClass.getId());
				pstmt.execute();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
		}
	}
	
	
	public void delete(Integer id) {
		String sql="delete from tbClass Where id="+id;
		Connection conn = ConnectionFactory.getConnection();
		if(conn!=null) {
			Statement stmt;
			try {
				stmt = conn.createStatement();
				stmt.execute(sql);
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
}
